package cn.db101.api.complex.component

import cn.dev33.satoken.exception.NotLoginException
import cn.db101.api.complex.component.Slf4j.Companion.log
import cn.db101.api.complex.enumration.ResultCodeEnum
import cn.db101.api.complex.model.WebResult
import com.wuhanpe.face.cloud.exception.AppComplexSignException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice


/**
 *
 * @author：zooooooooy
 * @date: 2022/7/5 - 23:55
 */
@RestControllerAdvice
@cn.db101.api.complex.component.Slf4j
class CustomControllerAdvice {

    @ExceptionHandler(Exception::class)
    fun exceptionHandler(exception: Exception): WebResult<Any> {

        log.error("system error: ", exception)
        return WebResult.wrapErrorResult(ResultCodeEnum.SYSTEM_ERROR)
    }

    @ExceptionHandler(NotLoginException::class)
    fun saTokenExceptionHandler(nle: NotLoginException): WebResult<Any> {

        // 判断场景值，定制化异常信息
        var message = if (nle.type.equals(NotLoginException.NOT_TOKEN)) {
            "未提供token"
        } else if (nle.type.equals(NotLoginException.INVALID_TOKEN)) {
            "token无效"
        } else if (nle.type.equals(NotLoginException.TOKEN_TIMEOUT)) {
            "token已过期"
        } else if (nle.type.equals(NotLoginException.BE_REPLACED)) {
            "token已被顶下线"
        } else if (nle.type.equals(NotLoginException.KICK_OUT)) {
            "token已被踢下线"
        } else {
            "当前会话未登录"
        }

        return WebResult.wrapErrorResult(ResultCodeEnum.FLUSHTOKEN, message)
    }

    @ExceptionHandler(AppComplexSignException::class)
    fun exceptionHandler(exception: AppComplexSignException): WebResult<Any> {

        return WebResult.wrapErrorResult(exception.codeEnum)
    }

}
